using Hcf.Logger.SignalR.Hubs;
using Hcf.Logger.SignalR.Logger;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Hcf.Logger.SignalR
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllersWithViews();
            builder.Services.AddSignalR();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<DataHub>("/DataHub");
            });

            IHubContext<DataHub> hubContext = app.Services.GetService<IHubContext<DataHub>>();
            app.Services.GetService<ILoggerFactory>().AddProvider(new SignalRLoggerProvider(new SignalRConfiguration { LogLevel = LogLevel.Debug }, hubContext));

            Task.Run(() =>
            {
                var logger = app.Services.GetService<ILogger<Program>>();
                Random rnd = new Random();

                while (true)
                {
                    int value = rnd.Next(0, 12);
                    if(value % 4 == 0)
                    {
                        logger.LogDebug($"Logger debug {value}");
                    }
                    else if (value % 4 == 1)
                    {
                        logger.LogInformation($"Logger information {value}");
                    }
                    else if (value % 4 == 2)
                    {
                        logger.LogWarning($"Logger warning {value}");
                    }
                    else if (value % 4 == 3)
                    {
                        logger.LogError($"Logger error {value}");
                    }

                    Thread.Sleep(2000);
                }
            });

            app.Run();
        }
    }
}